package org.sample.springbootcommon.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class EncodeUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(EncodeUtils.class);

	private EncodeUtils() {
		// Empty constructor.
	}

	public static String toBase64(byte[] bytes) {
		return Base64.getEncoder().encodeToString(bytes);
	}

	public static String toHex(byte[] bytes) {
		StringBuilder builder = new StringBuilder();
		for (byte b : bytes) {
			builder.append(String.format("%2x", b));
		}
		return builder.toString();
	}

	public static String toDigestBase64(byte[] bytes) {

		MessageDigest messageDigest;
		try {
			messageDigest = MessageDigest.getInstance("SHA-1");
		} catch (NoSuchAlgorithmException e) {
			LOGGER.error("No SHA-1 digest", e);
			return null;
		}

		byte[] digestBytes = messageDigest.digest(bytes);
		return toBase64(digestBytes);
	}

	public static String toDigestBase64(String text) {
		if (text == null) {
			return null;
		}
		return toDigestBase64(text.getBytes());
	}

	public static String toJsonDigestBase64(Object obj) {

		try {
			ObjectMapper mapper = new ObjectMapper();
			byte[] jsonBytes = mapper.writeValueAsBytes(obj);
			return toDigestBase64(jsonBytes);
		} catch (JsonProcessingException e) {
			LOGGER.error("Cannot convert to JSON", e);
			return "";
		}
	}

}
